package com.wanqh.reptitle;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.excel.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

public class SingatureUtil {

    private static final String FANS_SALT = "382700b563f4";

    public static String genSignature(Map<String,String> params,String salt) {
        if(params == null){
            return null;
        }
        String sign = "";
        StringBuffer sb = new StringBuffer();
        try {
            // 1. 字典升序排序
            SortedMap<String,String> sortedMap = new TreeMap<>(params);
            // 2. 拼按URL键值对
            Set<String> keySet = sortedMap.keySet();
            for(String key : keySet){
                //sign不参与算法
                if(key.equals("sig") || key.equals("__NStokensig")){
                    continue;
                }
                String value = sortedMap.get(key);
                sb.append(key + "=" + URLDecoder.decode(value,"UTF-8"));
            }
            String uriString = sb.toString();
            uriString = uriString + salt;
            System.out.println("My String: \n" + uriString);
            // 3. MD5运算得到请求签名
            MD5 md5 = MD5.create();
            sign = md5.digestHex(uriString);
//            sign = MD5Util.md5(uriString);
            System.out.println("My Sign:\n" +sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }

    public static Map<String,String> getMapFromStr(String str){
        if(StringUtils.isEmpty(str)){
            return null;
        }
        String[] arr = str.split("\\&");
        Map<String,String> map = new HashMap<>();
        for(String item : arr){
            String[] itemArr = item.split("=",2);
            map.put(itemArr[0],itemArr[1]);
        }
        return map;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String srcStr = "mod=HUAWEI%28Mate%2010%20Pro%29&lon=113.373227&country_code=CN&kpn=KUAISHOU&oc=GDT_YUNMENGFEED%2C13&egid=DFP625C148E1E30EB006E3185BDA69B8CB051B57E1E0F913F431DD0BC2816EC6&hotfix_ver=&sh=1280&appver=6.9.2.11245&max_memory=192&isp=&browseType=1&kpf=ANDROID_PHONE&did=ANDROID_8d734be0c87bcc81&net=WIFI&app=0&ud=1528314752&c=GDT_YUNMENGFEED%2C13&sys=ANDROID_6.0.1&sw=800&ftt=&language=zh-cn&iuid=&lat=23.126156&did_gt=1588407773244&ver=6.9";
        genSignature(getMapFromStr(srcStr),FANS_SALT);
    }
}


